import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, 
  Dimensions,ScrollView,Modal,
  TouchableOpacity,
} from 'react-native';
import SearchView from '../../component/SearchView';
import Loading from '../../component/Loading';
import {jumpPage} from '../../common/common'
import {BASEURL} from '../../api/api'
import NoData from '../../component/NoData';
import Search from './Search';
import BackButton from '../../component/BackButton';
const {height, width} = Dimensions.get('window');
var IMG_URL =  BASEURL+'image/showImage?imageName=';
let text1='行业';
let text2='用途';
export default class Templ extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      header:null,
    }
  };
  constructor(props){
    super(props);
    this.state = ({
			type:1,
			open:0,
			modal:false,
      topActive:0, //1-行业  2-用途
      loading:true,
			leftActive:-1,
			text1: text1,
			text2: text2,
      leftData:[

      ],
      data:[

			],
			industryList:[],
			useList:[],
			industry:'all',
			use:'all',
    })
  }
  componentWillMount(){
		this._getTypeList();
		this._getTempList(1,"1");
    
	}
	componentWillUnmount(){
		this.setState({
			modal:false
		})
	}
	//获取类型
	_getTypeList(){
    fetch(BASEURL+'temp/tempIndustryAndUse')
    .then(res=>res.json())
    .then(response=>{
			console.log('res--',response);
			response.industryList.unshift({typeName:'全部',tempTypeId:'all'})
			response.useList.unshift({typeName:'全部',tempTypeId:'all'})
      this.setState({
				industryList: response.industryList,
				useList: response.useList
      },()=>{

      })
    })
	}
	/*
  _getTypeList(){
    fetch(BASEURL+'temp/typeList?firstType='+this.state.topActive)
    .then(res=>res.json())
    .then(response=>{
			//console.log(response);
			response.list.unshift({typeName:'全部'})
      this.setState({
        leftData:response.list,
      },()=>{

      })
    })
  }*/
  _getTempList(typeId,type){
		let {industry, use} = this.state;
		console.log('state',this.state)
    fetch(BASEURL+'temp/listIndex?typeId='+industry+'&typeId2='+use)
    .then(res=>res.json())
    .then(response=>{
			//console.log(response);
			response.list.unshift({
				type:'add'
			})
      this.setState({
        loading:false,
        data:response.list,
      })
    })
  }
  _goDetail(tempId,tempTitle){
    jumpPage(this.props.navigation,'tempDetail',{tempId,tempTitle})
	}
	//创建空白模板
	_createTemp(){
		jumpPage(this.props.navigation,'createTemp',{tempTitle:'空白模板'})
	}
	//点击类型
  _leftSelect(index,tempTypeId, typeName){
		//console.log('333',tempTypeId)
		//alert(tempTypeId+','+typeName);
		let {industry,use} = this.state;
		if(this.state.topActive == 1){//行业
			industry = tempTypeId;
		} else { //用途
			use = tempTypeId;
		}
    this.setState({
			leftActive:index,
			industry:industry,
			use: use,
			modal:false,
      open:'0',
      topActive: 0
		},()=>{
			this._getTempList();
		})
		// if(index == 0){//全部
		// 	this._getTempList(this.state.topActive,1);
		// } else{
		// 	this._getTempList(tempTypeId,"2");
		// }
    
  }
  _topPress(type){
		if(type == 1){
			this.setState({
				topActive:type,
				modal:!this.state.modal,
        leftData: this.state.industryList,
        open: type
			})
		} else {
			this.setState({
				topActive:type,
				modal:!this.state.modal,
        leftData: this.state.useList,
        open: type
			})
		}
		/*
		if(type != this.state.topActive){
			this.setState({
				leftActive:-1,
			})
		}
    this.setState({
			open: type,
			topActive: type,
			modal:!this.state.modal,
    },()=>{
      this._getTypeList();
		})
		*/
  } 
  _renderLeft(){
		let {leftData} = this.state;
		console.log('leftData',leftData)
    if(leftData.length == 0) return;
    var leftCell = [];
    for(let i=0; i<leftData.length; i++){
      let item = leftData[i];
      leftCell.push(
        <TouchableOpacity key={i} onPress={()=>{this._leftSelect(i,item.tempTypeId)}} activeOpacity={0.6}
          style={styles.leftCellView}>
          <View  style={[styles.leftCell,i==this.state.leftActive?styles.leftCellActive:null]}>
            <Text style={[styles.typeText,i==this.state.leftActive?styles.typeTextActive:null]}>{item.typeName}</Text>
          </View>
          
        </TouchableOpacity>
      )
    }
    return leftCell;
	}
	renderType(){
		let {leftData} = this.state;
    if(leftData.length == 0) return;
		var leftCell = [];
		let selectId = '';
		if(this.state.topActive == 1){
			selectId = this.state.industry;
		} else {
			selectId = this.state.use;
		}
    for(let i=0; i<leftData.length; i++){
      let item = leftData[i];
      leftCell.push(
        <TouchableOpacity key={i} activeOpacity={0.9} onPress={()=>{this._leftSelect(i,item.tempTypeId,item.typeName)}}
          style={styles.leftCellView}>
          <View  style={[styles.leftCell,item.tempTypeId == selectId ? styles.leftCellActive:null]}>
            <Text style={[styles.typeText,item.tempTypeId == selectId ? styles.typeTextActive:null]}>{item.typeName}</Text>
          </View>
        </TouchableOpacity>
      )
    }
    return leftCell;
	}
  _renderContent(){
    let {data} = this.state;
    // data.map((item, index) => (
    //   <Cell  key={index}   style={{marginBottom:index==data.length-1?0:0}}
    //   press={()=>this._goDetail(item.tempId,item.tempTitle)} data={item} />
    // ))
    var rightCell = [];
    for(let i=0; i<data.length; i++){
			let item = data[i];
			if(item.type && item.type == 'add'){
				rightCell.push(
					<TouchableOpacity style={[styles.cellViewStyle,]} key='add' 
						activeOpacity={0.6} onPress={()=>{this._createTemp()}}>
						<View style={[styles.cellImg, {borderWidth:0,borderColor:'#ccc',
						height:(width-4)/2/16*9+20,
						backgroundColor:'#fff',justifyContent:'center',alignItems:'center'}]}>
							<Image style={{width:30,height:30}} source={require('../../images/temp/add_img.png')}/>
						</View>
					</TouchableOpacity>
				)
			} else {
				rightCell.push(
					<Cell  key={i}   
					press={()=>this._goDetail(item.tempId,item.tempTitle)} data={item} />
				)
			}
    }
    return rightCell;
  }
  render(){
    //console.log('len',this.state.data.length)
    let topActive = this.state.topActive;
    const topStyle={
      paddingTop:10,
      paddingBottom:10,
      fontSize:15
    }
    const viewStyle = {
			paddingLeft:10,
			paddingRight:10,
			flexDirection:'row',
      justifyContent:'center',
      alignItems:'center',
      // borderWidth:StyleSheet.hairlineWidth,
      // borderColor: '#ccc'
		}
		let imgDown = require('../../images/arrow_down.png');
		let imgUp = require('../../images/arrow_up.png');
		let arrowStyle={
			width:14,
			height:20,
			resizeMode:'stretch',
			marginLeft:10,
		}
		let open = this.state.open;
		let noData = false;
		if(!this.state.data || this.state.data.length==0){
			noData = true;
		}
    return(
      <View style={styles.container}>
        <View style={{flexDirection:'row',alignItems:'center',marginTop:10}}>
          
					{/* <SearchView style={{paddingLeft:0}} placeholder='搜索你喜欢的'/> */}
					{/* <BackButton/> */}
					<Search placeholder='搜索您想要的模板...'
						style={{paddingLeft:0,borderRadius:10,marginRight:10,marginLeft:10}}
            search={()=>this._search()} 
            onChange={(val)=>this._onChange(val)}
            />
        </View>
        <View style={styles.content}>
          <View style={{flexDirection:'row',justifyContent:'flex-start',backgroundColor:'#f0f0f0'}}>
            <TouchableOpacity style={[viewStyle,{backgroundColor:topActive==1?'white':'#eee'}]} onPress={()=>{this._topPress(1)}}>
              <Text style={topStyle}>{this.state.text1}</Text>
							<Image source={open==1?imgUp:imgDown} style={arrowStyle}/>
            </TouchableOpacity>
            <TouchableOpacity style={[viewStyle,{backgroundColor:topActive==2?'white':'#eee'}]} onPress={()=>{this._topPress(2)}}>
              <Text style={topStyle}>{this.state.text2}</Text>
							<Image source={open==2?imgUp:imgDown} style={arrowStyle}/>
            </TouchableOpacity>
            {/* <TouchableOpacity style={[viewStyle,{backgroundColor:topActive==3?'white':'#eee'}]} onPress={()=>{this._topPress(3)}}>
              <Text style={topStyle}>其它</Text>
							<Image source={open==1?imgUp:imgDown} style={arrowStyle}/>
            </TouchableOpacity> */}
          </View>
          {/* <View style={styles.leftView}>
            {this._renderLeft()}
          </View> */}
          { this.state.loading ? <Loading/> : 
          (
            noData ? <NoData /> :
            <ScrollView style={{flex:1}}>
              <View style={styles.rightView}>
              {this._renderContent()}
              </View>
            </ScrollView>
          )
          }
					<Modal animationType='none' 
						transparent={true} 
						visible={this.state.modal} 
						onRequestClose={() => {this.setState({modal:false})}}
						style={{borderColor:'green',borderWidth:5}}
						>
						<View style={{backgroundColor:'rgba(0, 0, 0, 0.0)',flex:1}}>
							<View style={[styles.leftView,{marginTop:100,backgroundColor:'white'}]}>
								{this.renderType()}
							</View>
						</View>
						
        	</Modal>
        </View>
      </View>
    )
  }
}
class Cell extends Component{
  render(){
    let img = this.props.data.tempImg;
    if(img && img.indexOf('http') == -1){
      img = IMG_URL + img;
    }
    return(
      <TouchableOpacity style={[styles.cellViewStyle,this.props.style]} activeOpacity={0.6} onPress={this.props.press}>
        <Image style={styles.cellImg} source={{uri:img}}/>
        <Text style={styles.cellText}>{this.props.data.tempTitle}</Text>
      </TouchableOpacity>
    )
  }
}
const styles = StyleSheet.create({
  cellViewStyle:{
    marginTop:0,
    marginBottom:5,
    marginLeft:0,
    width:(width-10)/2,
		backgroundColor:'#fff',
		padding:5,
    // borderWidth:StyleSheet.hairlineWidth,
    // borderColor:'black',
    // paddingBottom:8,
		shadowColor: 'rgba(0, 0, 0, 0.8)',
    shadowOffset: {
        width: 10,
        height: 3
    },
    shadowRadius: 2,
    elevation: 4,
  },
  cellText:{
    color: '#555',
    padding:5,
    paddingLeft:8,
  },
  cellImg:{
    width:(width-10)/2-10,
    height:((width-10)/2-10)/16*9,
  },
  typeText:{
		//color:'#0066FF'
		color:'#555'
  },
  typeTextActive:{
    color:'white',
  },
  leftCellView:{
    width:'25%',
    backgroundColor:'white'
  },
  leftCell:{
    paddingTop:2,
    paddingBottom:2,
    paddingLeft:5,
    paddingRight:5,
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'white',
    borderWidth:1,
		//borderColor:'#0066FF',
		borderColor:'white',
    marginLeft:10,
    marginRight:10,
    marginTop:5,
    marginBottom:5,
    borderRadius:20,
  },
  leftCellActive:{
    backgroundColor:'#0066FF',
    borderLeftColor:'#d71470',
    borderWidth:1,
  },
  leftView:{
    flexDirection:'row',
    flexWrap:'wrap',
    borderBottomWidth:StyleSheet.hairlineWidth,
    borderColor:'#aaa',
    paddingBottom:5,
    // borderWidth:1,
    // borderColor:'gray',
    //width:width/4,
  },
  rightView:{
    paddingLeft:0,
    // borderWidth:1,
    // borderColor:'green',
    flex:1,
    height:'100%',
    flexDirection:'row',
    justifyContent:'space-between',
    flexWrap:'wrap',
  },
  content:{
    //flexDirection:'row',
		flex:1,
		marginTop:10,
    // borderWidth:1,
    // borderColor:'red',
  },
  headerText:{
    fontSize:17,
    color:'#555',
    padding:10,
  },
  container: {
		backgroundColor:'#f0f0f0',
    flex: 1,
    marginTop:0,
  },
})